#! /usr/bin/env python  
#encoding: utf-8
# -*- coding: utf-8 -*-  
# 解析数据库的设计（excel的读取） 
#
# excel中必须有一个index的sheet，记录表的信息 
# 文件模板：http://docs.makotemplates.org/en/latest/ 

#  https://pypi.python.org/pypi/xlrd
#  sudo ./setup.py install

#  http://www.makotemplates.org
#  sudo python setup.py install 
#
#@author yuqingxu@ctrip.com  
#@version 2016-06-06  11:00


import os
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import json
import getopt
import xlrd
from mako.template import Template
from mako.lookup import TemplateLookup
from mako import exceptions
from mako.exceptions import RichTraceback

sourceFile = "../docs/数据库设计.xlsx"
tables = []
lookup = TemplateLookup(directories=['template'], input_encoding='utf-8',output_encoding='utf-8', encoding_errors='replace')
templateFile = {'modelTemplate':'model.txt',"daoTemplate":"dao.txt"}
outRoot = '../src/main/java/'
# outRoot = '../out/'
moduleConfig = "../src/main/java/com/fruit/soa/ModuleConfig.java"
daoStartTag = "flag:DAO"
EndTag = "/*********************"

def parseArgus():
    # print 'parse the arguments'
    global sourceFile
    # if len(sys.argv) >0:
    #     for i in range(1,len(sys.argv)):
    #         print '参数',i,sys.argv[i]
    opts,args = getopt.getopt(sys.argv[1:],"i:o:")
    for op,value in opts:
        if op == "-i":
            sourceFile = value
        
def getAllTables():
    print '加载表信息。。。'
    data = xlrd.open_workbook(sourceFile)
    indexPage = data.sheet_by_name(u'index')

    for i in range(indexPage.nrows):    
        if i == 0:
            continue    
        # print "row",i,indexPage.cell(i,1).value
        tableInfo = {}
        tableInfo["name"] = indexPage.cell(i,1).value
        tableInfo["desc"] = indexPage.cell(i,2).value              
        tableInfo["objName"] = indexPage.cell(i,4).value        
        tableInfo["daoPackageName"] = indexPage.cell(i,3).value+"."+ indexPage.cell(i,5).value    
        tableInfo["modelPackageName"] = indexPage.cell(i,3).value+"."+ indexPage.cell(i,6).value
        tableInfo["dao"] = indexPage.cell(i,5).value
        tableInfo["model"] = indexPage.cell(i,6).value
        tables.append(tableInfo)

def getTableInfo(table):
    print '加载表[',table["name"],'] 内容'
    cols = []
    data = xlrd.open_workbook(sourceFile)
    tablePage = data.sheet_by_name(table["name"])
    for i in range(tablePage.nrows) :
        if i == 0:
            continue     
        if len(tablePage.cell(i,1).value) ==0:
            return cols            
        # print 'row no:',i ,' value:',tablePage.cell(i,0).value        
        colInfo = {}
        colInfo["name"] = tablePage.cell(i,1).value
        colInfo["type"] = tablePage.cell(i,2).value
        colInfo["maxNum"] = tablePage.cell(i,3).value
        colInfo["primaryKey"] = tablePage.cell(i,4).value
        colInfo["foreignKey"] = tablePage.cell(i,5).value
        colInfo["nullEnable"] = tablePage.cell(i,6).value
        colInfo["identity"] = tablePage.cell(i,7).value
        colInfo["defaultValue"] = tablePage.cell(i,8).value
        colInfo["lanType"] = tablePage.cell(i,9).value
        colInfo["desc"] = tablePage.cell(i,10).value
        cols.append(colInfo) 
    return cols

def genModelFile(table,templateFile):    
    try:
        templateObj = lookup.get_template(templateFile)
        fileContext = templateObj.render(item=table)
        targetFile = outRoot+table["modelPackageName"].replace('.','/')+'/'+table["objName"]+'Model.java'
        if fileContext == None or fileContext == "" :
            print '内容为空:',targetFile
        else:                 
            if not os.path.exists(os.path.dirname(targetFile)) :                
                os.makedirs(os.path.dirname(targetFile))
            if os.path.exists(targetFile):
                os.remove(targetFile)
            outFile = open(targetFile,'w')
            outFile.write(fileContext)
            outFile.close()
            print '生成model文件：',targetFile
    except:
        # print exceptions.text_error_template().render()
        # print exceptions.html_error_template().render()
        traceback = RichTraceback()
        for (filename, lineno, function, line) in traceback.traceback:
            print 'File %s, line %s, in %s' % (filename, lineno, function)
            print line, '\n'
        print '%s: %s' % (str(traceback.error.__class__.__name__), traceback.error)

def clearDaoDefine():
    fp = file(moduleConfig)
    lines = []
    startLineNum = 1
    endLineNum = 1
    index = 0
    flag = "N"    
    offset = 0   
    for line in fp:
        
        if startLineNum == 1 and line.find(daoStartTag) != -1:
            startLineNum = index            
        if startLineNum > 1 and endLineNum == 1 and line.find(EndTag) != -1:
            endLineNum = index

        if startLineNum > 1 and endLineNum == 1:
            offset = offset + 1        
            

        if (startLineNum == 1 and endLineNum == 1) or (offset <= 4 and startLineNum > 1) or (startLineNum > 1 and endLineNum > 1) :
           lines.append(line) 


        index = index + 1
    fp.close()

    s = ''.join(lines)
    fp = file(moduleConfig, 'w')
    fp.write(s)
    fp.close()



def appendDaoDefine(tableName,desc):
    print '修改ModuleConfig中的Dao配置'
    addStr = "ADDR_SOA_DAO_"+tableName.upper()+"_ADD"
    # print addStr
    fp = file(moduleConfig)
    lines = []
    startLineNum = 1
    endLineNum = 1
    hasExist = "N"
    index = 0 
    for line in fp:
        index = index + 1
        # print line
        lines.append(line)
        if startLineNum == 1 and line.find(daoStartTag) != -1:
            startLineNum = index
            # print "startLine:",startLineNum
        if startLineNum >1 and endLineNum  == 1 and line.find(EndTag) != -1 :
            endLineNum = index
            # print "endLine:",endLineNum
        if startLineNum >1 and endLineNum  == 1 and line.strip().find(addStr) != -1 :
            # print addStr,"    ",line
            hasExist = "Y"            
    fp.close()

    # print hasExist
    if hasExist == "N" :
        # print '开始插入'
        endLineNum = endLineNum - 2
        # print endLineNum
        lines.insert(endLineNum,""+"\n")
        lines.insert(endLineNum,"    public final static String ADDR_SOA_DAO_"+tableName.upper()+"_DEL = \"addr_soa_dao_"+tableName.lower()+"_del\";"+"\n")
        lines.insert(endLineNum,"    public final static String ADDR_SOA_DAO_"+tableName.upper()+"_MOD = \"addr_soa_dao_"+tableName.lower()+"_mod\";"+"\n")
        lines.insert(endLineNum,"    public final static String ADDR_SOA_DAO_"+tableName.upper()+"_ADD = \"addr_soa_dao_"+tableName.lower()+"_add\";"+"\n")        
        lines.insert(endLineNum,""+"\n")
        lines.insert(endLineNum,"     */"+"\n")
        lines.insert(endLineNum,"     * "+desc+"\n")
        lines.insert(endLineNum,"    /**"+"\n")
        lines.insert(endLineNum,""+"\n")
    s = ''.join(lines)
    fp = file(moduleConfig, 'w')
    fp.write(s)
    fp.close()

def genDaoFile(table,templateFile):
    try:
        templateObj = lookup.get_template(templateFile)
        fileContext = templateObj.render(item=table)
        targetFile = outRoot+table["daoPackageName"].replace('.','/')+'/'+table["objName"]+'Dao.java'
        if fileContext == None or fileContext == "" :
            print '内容为空:',targetFile
        else:                 
            if not os.path.exists(os.path.dirname(targetFile)) :                
                os.makedirs(os.path.dirname(targetFile))
            if os.path.exists(targetFile):
                os.remove(targetFile)
            outFile = open(targetFile,'w')
            outFile.write(fileContext)
            outFile.close()
            print '生成dao文件：',targetFile
            appendDaoDefine(table["name"],table["desc"])
    except:
        # print exceptions.text_error_template().render()
        # print exceptions.html_error_template().render()
        traceback = RichTraceback()
        # for (filename, lineno, function, line) in traceback.traceback:
        #     print 'File %s, line %s, in %s' % (filename, lineno, function)
        #     print line, '\n'
        print '%s: %s' % (str(traceback.error.__class__.__name__), traceback.error)   


    

if __name__ == "__main__":
    parseArgus()
    print "sourceFile",sourceFile
    getAllTables()
    

    clearDaoDefine()
    for i in range(len(tables)):
        table = tables[i]
        table["cols"] = getTableInfo(table)
        genModelFile(table,templateFile["modelTemplate"])
        genDaoFile(table,templateFile["daoTemplate"])
        
    # print '======'
    # print json.dumps(tables,indent=1, encoding='UTF-8', ensure_ascii=False)
    
    





